/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modules.estoque.gui.jpanel;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import modules.estoque.bo.ConstanteMensagem;
import modules.estoque.facade.WMSFacade;
import modules.estoque.gui.custom.WMSJTextField;
import modules.estoque.models.dto.Produto;
import modules.estoque.util.BoxPanel;

/**
 *
 * @author Usuario
 */
public class FrameProdutoPesquisa extends javax.swing.JFrame {

    WMSJTextField tfCodigoPai;
    WMSJTextField tfDescricaoPai;
    WMSJTextField tfFocusPai;
    
    /**
     * Creates new form FrameProdutoPesquisa
     */
    public FrameProdutoPesquisa() {
        initComponents();
    }
    
    public FrameProdutoPesquisa(WMSJTextField tfCodigoPai,WMSJTextField tfDescricaoPai,WMSJTextField tfFocusPai) {
        initComponents();
        this.tfCodigoPai = tfCodigoPai;
        this.tfDescricaoPai = tfDescricaoPai;
        this.tfFocusPai = tfFocusPai;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        wMSLabel3 = new modules.estoque.gui.custom.WMSLabel();
        tfCodigo = new modules.estoque.gui.custom.WMSJTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new modules.estoque.gui.custom.WMSJTable();
        btnConfirmar = new modules.estoque.gui.custom.WMSJButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        wMSLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        wMSLabel3.setText("Buscar por:");

        tfCodigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfCodigoFocusLost(evt);
            }
        });
        tfCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfCodigoKeyPressed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Descrição"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTable1);

        btnConfirmar.setText("Confirmar");
        btnConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(wMSLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(197, 197, 197)
                        .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wMSLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfCodigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfCodigoFocusLost

    }//GEN-LAST:event_tfCodigoFocusLost

    private void tfCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfCodigoKeyPressed
        if(!tfCodigo.getText().equals("")){
            preencherGradeProdutos(
                new WMSFacade().obterProdutos("FROM Produto WHERE descricao like '%"+tfCodigo.getText()+"%' AND ativo=true")
            ); 
        }else{
            preencherGradeProdutos(new ArrayList()); 
        }
    }//GEN-LAST:event_tfCodigoKeyPressed

    private void btnConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarActionPerformed
        if (jTable1.getSelectedRowCount() > 0) {
            DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
            int selected = jTable1.getSelectedRow();
            Integer id = (Integer) modelo.getValueAt(selected, 0);
            String descricao = (String) modelo.getValueAt(selected, 1);
            tfCodigoPai.setText(id.toString());
            tfDescricaoPai.setText(descricao);   
            tfFocusPai.requestFocus();   
            try {
                this.dispose();
            } catch (Throwable ex) {
                Logger.getLogger(FrameProdutoPesquisa.class.getName()).log(Level.SEVERE, null, ex);
            }
        }else{
            BoxPanel.showMessageDialog(null, ConstanteMensagem.REGISTRO_NAO_SELECIONADO);
        }
    }//GEN-LAST:event_btnConfirmarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrameProdutoPesquisa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrameProdutoPesquisa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrameProdutoPesquisa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrameProdutoPesquisa.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrameProdutoPesquisa().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private modules.estoque.gui.custom.WMSJButton btnConfirmar;
    private javax.swing.JScrollPane jScrollPane1;
    private modules.estoque.gui.custom.WMSJTable jTable1;
    private modules.estoque.gui.custom.WMSJTextField tfCodigo;
    private modules.estoque.gui.custom.WMSLabel wMSLabel3;
    // End of variables declaration//GEN-END:variables
    private void preencherGradeProdutos(List<Produto> produtos){
        jTable1.getColumnModel().getColumn(0).setPreferredWidth(1);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(200);

        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        modelo.setNumRows(0);

        for (int i = 0; i < produtos.size(); i++) {
            int id = produtos.get(i).getId();
            String descricao = produtos.get(i).getDescricao();
            
            modelo.addRow(new Object[]{
                        id, descricao
                    });
        }
    }

}
